<template>
	<view class="container">
		<view class="list-bar" :style="{paddingBottom: sattleMoney > 0 ? '140rpx' : '32rpx'}">
			<view v-if="list.length === 0 && !loading" class="empty-state">
				<u-icon name="info-circle" size="80" color="#CCCCCC"></u-icon>
				<view class="empty-text">暂无账单信息</view>
				<view class="empty-tips">您当前没有待支付的账单</view>
			</view>
			<view class="list-item" @click="handleCheck(item, index)" v-for="(item, index) in list" :key="index">
				<view class="list-item__checkbox" :class="{'is-active': item.checked}">
					<u-icon name="checkbox-mark" color="#FFF"></u-icon>
				</view>
				<view class="list-item__content">
					<view class="">{{ item.name }}</view>
					<view class="">{{ item.roomDetail.buildingName }}{{ item.roomDetail.name }}</view>
					<view class="">应付时间：{{ formatDate(item.noticeDate) }}</view>
				</view>
				<view class="list-item__arrow-right">
					<view class="list-item__billing">{{ item.money }}元</view>
					<u-icon name="arrow-right"></u-icon>
				</view>
				<view class="list-item__tip" v-if="item.overdue">
					{{item.overdue}}
				</view>
			</view>
			<u-loadmore :status="status" v-if="list.length > 0 || loading" />
		</view>
		<view class="settle-bar" v-if="sattleMoney > 0">
			<view class="settle-money">
				{{ sattleMoney.toFixed(2) }} 元
			</view>
			<u-button type="success" size="medium" @click="handlePay">去支付</u-button>
		</view>
	</view>
</template>

<script>
	import { billList, billPay } from '@/api/bill/index.js'
	import { checkPaymentStatus } from '@/utils/common.js'
	import { greet } from '@/api/login.js'
	import dayjs from 'dayjs'
	export default {
		data() {
			return {
				check: false,
				status: 'loadmore',
				roomId: "",
				params: {
					roomId: "",
					pageNum: 1,
					pageSize: 10,
				},
				list: [],
				paymentLoading: false,
				orderNo: '',
				loading: false,
			}
		},
		computed: {
			sattleMoney() {
				let total = 0
				this.list.forEach(item => {
					if (item.checked) {
						total += Number(item.money)
					}
				})
				return total
			}
		},
		onReachBottom() {
			if (this.list.length >= this.total) {
				this.status = 'nomore'
			} else {
				this.params.pageNum++;
				this.getList()
			}
		},
		onLoad(params) {
			console.log(params)
			this.roomId = params.roomId;
			this.params.roomId = params.roomId;
			this.getList();
		},
		onPullDownRefresh() {
			this.params.pageNum = 1
			this.list = []
			this.getList();
		},
		methods: {
			formatDate(date) {
				return dayjs(date).format("YYYY-MM-DD")
			},
			handleCheck(row, index) {
				// 账单点击事件
				if (row.checked) {
					this.list.forEach((item, originIndex) => {
						if (originIndex >= index) {
							item.checked = false
						}
					})
					return
				}
				this.list.forEach((item, originIndex) => {
					if (originIndex <= index) {
						item.checked = true
					}
				})
			},
			getList() {
				this.status = 'loading'
				this.loading = true
				billList(this.params).then(res => {
					this.total = res.total;
					res.rows.forEach(item => {
						item.checked = false;
						console.log(dayjs(item.noticeDate).diff(new Date(), "day"));
						if (dayjs(item.noticeDate).diff(new Date(), "day") < 0) {
							item.overdue = "已逾期"
						} else if (dayjs(item.noticeDate).diff(new Date(), "day") <= 7) {
							item.overdue = "即将到期"
						} else {
							item.overdue = ""
						}
						this.list.push(item)
					})
					this.status = 'loadmore'
					this.loading = false
				}).catch(() => {
					this.loading = false
				})
				console.log(this.list)
				
			},
			async handlePay() {
				if (this.paymentLoading) return
				
				try {
					this.paymentLoading = true
					
					// 获取选中的账单ID列表
					const billIds = this.list
						.filter(item => item.checked)
						.map(item => item.billId)

					let openid = ''
					uni.login({
						success: async (res) => {
							if (res.code) {
								let greetRes = await greet(res.code)
								// 获取openid 绑定
								console.log(greetRes);
								openid = greetRes.data.openid
								
								if (billIds.length === 0) {
									uni.showToast({
										title: '请选择需要支付的账单',
										icon: 'none'
									})
									return
								}
								
								// 创建支付订单
								const orderRes = await billPay({
									billIds: billIds.join(','),
									money: this.sattleMoney,
									onpenId: openid
								})
								
								this.orderNo = orderRes.data.orderNo
								
								// 调起微信支付
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: orderRes.data.timeStamp,
									nonceStr: orderRes.data.nonceStr,
									package: orderRes.data.package,
									signType: orderRes.data.signType,
									paySign: orderRes.data.paySign,
									success: async (res) => {
										// 支付成功后轮询订单状态
										let isSuccess = await checkPaymentStatus(0, this.orderNo)
										if (isSuccess) {
											uni.showToast({
												title: '支付成功',
												icon: 'success'
											})
											
											// 刷新账单列表
											this.params.pageNum = 1
											this.list = []
											this.getList()
										}
									},
									fail: (err) => {
										console.error('支付失败:', err)
										uni.showToast({
											title: '支付失败，请重试',
											icon: 'none'
										})
									},
									complete: () => {
										this.paymentLoading = false
									}
								})
							}
						}
					})

					

				} catch (error) {
					console.error('支付异常:', error)
					uni.showToast({
						title: error.message || '支付异常，请重试',
						icon: 'none'
					})
					this.paymentLoading = false
				} finally {
					this.paymentLoading = false
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.list-bar {
		height: 100%;
		// margin-bottom: 140rpx;
		padding: 32rpx;
		overflow-y: auto;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}

	.empty-text {
		margin-top: 30rpx;
		font-size: 32rpx;
		color: #666;
		font-weight: 500;
	}

	.empty-tips {
		margin-top: 16rpx;
		font-size: 26rpx;
		color: #999;
	}

	.list-item {
		position: relative;
		width: 100%;
		padding: 32rpx 32rpx 32rpx 20rpx;
		background-color: #FFF;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
	}
	.list-item__checkbox {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		border: 1px solid #bababa;
		margin-right: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.list-item__checkbox.is-active {
		background-color: dodgerblue;
		border: unset;
	}
	.list-item__content {
		line-height: 1.4em;
	}
	.list-item__arrow-right {
		position: absolute;
		right: 32rpx;
		top: 50%;
		transform: translateY(-50%);
		display: flex;
		align-items: center;
	}
	.list-item__billing {
		margin-right: 20rpx;
		color: #ff9900;
	}
	.list-item__tip {
		position: absolute;
		right: 0;
		top: 0;
		padding: 4rpx 12rpx;
		font-size: 20rpx;
		border-bottom-left-radius: 10rpx;
		border-top-right-radius: 10rpx;
		color: #fa3534;
		background-color: #fdf6ec;
	}

	.settle-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 120rpx;
		padding: 0 32rpx 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;
		box-shadow: 0 -2rpx 8rpx 2rpx #eee;
		z-index: 9;
	}
	.settle-money {
		font-size: 36rpx;
		color: #ff9900;
	}
</style>
